<template>
  <view class="container">
    <view class="list-container">
      <view class="top-container">
        <u-button type="primary" size="small" style="width: 120rpx;margin: 0" text="全选" @click="selectAll"></u-button>
        <u-button type="primary" size="small" style="width: 120rpx;margin: 0 0 0 20rpx;" text="清空"
                  @click="clear"></u-button>
      </view>
      <up-list style="height: 100%;">
        <up-checkbox-group v-model="selectValue" placement="column">
          <up-list-item v-for="(item, index) in rfidList" :key="index">
            <view class="list-item" @click="handlerClick(item)">
              <up-checkbox :key="item.name" :name="item.name" :disabled="item.disabled"></up-checkbox>
              <span>{{ item.name }}</span>
              <span>{{ item.status }}</span>
            </view>
          </up-list-item>
        </up-checkbox-group>
      </up-list>
    </view>
    <view class="form-container">
      <!-- 标签规格 -->
      <view class="form-item">
        <view class="form-label">标签规格</view>
        <view class="form-input">
          <u-input v-model="formData.label_specification" placeholder="请输入标签规格" border="none"></u-input>
        </view>
      </view>

      <!-- 天线规格 -->
      <view class="form-item">
        <view class="form-label">天线规格</view>
        <view class="form-input">
          <u-input v-model="formData.antenna_specification" placeholder="请输入天线规格" border="none"></u-input>
        </view>
      </view>

      <!-- 芯片规格 -->
      <view class="form-item">
        <view class="form-label">芯片规格</view>
        <view class="form-input">
          <u-input v-model="formData.chip_specification" placeholder="请输入芯片规格" border="none"></u-input>
        </view>
      </view>

      <!-- 标签材质 -->
      <view class="form-item">
        <view class="form-label">标签材质</view>
        <view class="form-input">
          <u-input v-model="formData.label_material" placeholder="请输入标签材质" border="none"></u-input>
        </view>
      </view>

      <!-- 标签类型 -->
      <view class="form-item">
        <view class="form-label">标签类型</view>
        <view class="form-input">
          <u-input v-model="formData.label_type" placeholder="请输入标签类型" border="none"></u-input>
        </view>
      </view>

      <view class="submit-btn">
        <u-button type="primary" text="提 交" style="width: 90%;" @click="submitForm"></u-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import {ref} from 'vue';
import http from "@/api/request";
import {onLoad} from "@dcloudio/uni-app";

const rfidList = ref([])
const formData = ref({
  label_code: '',
  label_specification: '',
  antenna_specification: '',
  chip_specification: '',
  label_material: '',
  label_type: 'RFID',
  usage_status: 'NOT_USED'
});
const selectValue = ref([])

onLoad((options) => {
  (options?.items ?? '').split(',').forEach(item => {
    rfidList.value.push({
      name: item,
      checked: false,
      disabled: false,
      status: ''
    })
  })
  selectValue.value = rfidList.value.map(item => item.name)
  if (rfidList.value.length > 0) {
    getViewTable()
  }
})

const selectAll = () => {
  const list = rfidList.value.filter(item => !item.disabled).map(item => item.name)
  selectValue.value = [...list]
}

const clear = () => {
  selectValue.value = []
}

const handlerClick = (item) => {
  if (selectValue.value.includes(item.name)) {
    selectValue.value = [...selectValue.value.filter(name => name !== item.name)]
  } else {
    selectValue.value.push(item.name)
  }
}

const getViewTable = () => {
  const params = {
    "code": "getTagsByCondition",
    "allColumnFilter": true,
    "filters": [{"name": "label_codes", "value": rfidList.value.map(item => item.name).join(',')}],
    "pageInput": {"currentPage": 1, "pageSize": 999},
    "permissionKey": ""
  }
  http.post("/api/module/GetViewTable", params).then(res => {
    const resultList = res.result?.viewTable ?? []
    const resultArr = resultList.map(item => item.label_code)
    rfidList.value.filter(item => resultArr.includes(item.name)).forEach(item => {
      item.status = '已存在'
      item.checked = false
      item.disabled = true
      selectValue.value = [...selectValue.value.filter(name => name !== item.name)]
    })
  }).catch(err => {
    console.error(err)
  })
}

const submitForm = () => {
  if (selectValue.value.length === 0) {
    uni.showToast({
      title: '请选择标签',
      icon: 'none'
    })
    return
  }
  const saveDataList = selectValue.value.map(item => ({
    ...formData.value,
    label_code: item
  }))
  // 显示加载中
  uni.showLoading({
    title: '提交中...'
  });
  // 构建请求参数
  const data = {
    "pageId": "eaab2c33-446a-4658-99d9-9a346382cc7b",
    "methodName": "doSaveTableData",
    "saveTableDataRequest": {
      "data": {
        "insert": {
          "tagmstr": {
            "data": saveDataList
          }
        },
        "update": {},
        "remove": {},
        "updateWhere": {},
        "removeWhere": {},
        "otherData": {"fileAttachments": []},
        "savedInvoke": {},
        "pageAuths": []
      }
    }
  };

  // 调用接口
  http.post("/api/module/Invoke", data).then((res) => {
    uni.hideLoading();

    if (res.isSuccess) {
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      });
      // 触发全局事件，通知列表页刷新数据
      uni.$emit('labelDataChanged');
      // 提交成功后返回上一页
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/label/label'
        })
      }, 1500);
    } else {
      uni.showToast({
        title: res.error || '提交失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    uni.hideLoading();
    console.error('保存标签失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
}

</script>

<style scoped lang="scss">
.container {
  height: calc(100vh - var(--window-top, 0px));
  width: 100vw;

  .list-container {
    height: 40%;
    width: 100%;
    padding: 20rpx;

    .top-container {
      display: flex;
      flex-direction: row;
    }
  }

  .form-container {
    margin-top: 60rpx;
    background-color: #FFFFFF;
    height: calc(60% - 60rpx);
    width: 100%;

    .form-item {
      display: flex;
      padding: 30rpx;
      border-bottom: 1px solid #f0f0f0;
    }

    .form-label {
      width: 200rpx;
      font-size: 30rpx;
      color: #333;
    }

    .submit-btn {
      width: 100%;
      color: #fff;
      margin-top: 10%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.required::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4rpx;
}

.form-input {
  flex: 1;
}

.list-item {
  width: 100%;
  margin: 10rpx 0;
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: white;
  border: 10rpx;
  padding: 20rpx;

  span {
    margin-left: 20rpx;
  }

  span:last-child {
    margin-left: auto;
  }
}
</style>